﻿using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using MinecraftEnchantCalculator.Data.Entity;

namespace MinecraftEnchantCalculator.Converters.Json;

public class ItemConverter : JsonConverter<Item>
{
  public override Item Read(
    ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options
  )
  {
    using var doc = JsonDocument.ParseValue(ref reader);
    var root = doc.RootElement;

    var code = root.GetProperty("Code").GetInt32();
    var name = root.GetProperty("Name").GetString() ?? string.Empty;
    var base64Icon = root.GetProperty("ItemBase64Icon").GetString();

    byte[] iconBytes;
    try {
      iconBytes = string.IsNullOrEmpty(base64Icon)
        ? Array.Empty<byte>()
        : Convert.FromBase64String(base64Icon);
    }
    catch (Exception /* ex */) {
      // Console.WriteLine(e);
      // throw;
      iconBytes = Array.Empty<byte>();
    }

    return new Item(code, name, iconBytes);
  }

  public override void Write(
    Utf8JsonWriter writer, Item value, JsonSerializerOptions options
  )
  {
    throw new NotSupportedException("Readonly Json entity write is not supported");
  }
}